package com.gorkr.offer.array;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author gorkr
 * @date 2022/04/09 10:14
 * [1234
 * 5678
 * 9101112
 * 13141516
 * [123568745]
 **/

/**
 * 学习收获：
 * 注意跳出循环的条件
 * ArrayList<Integer>转int[] result.stream().mapToInt(Integer::valueOf).toArray();
 */
public class OfferEasy29 {
    // List 如何转为Int 数组
    public int[] spiralOrder(int[][] matrix) {
        // 控制边界的题
        ArrayList<Integer> result = new ArrayList<>();

        int left,right,top,bottom;
        top=0;
        bottom=matrix.length;
        if(bottom==0){
            return new int[]{};
        }
        left=0;
        right=matrix[0].length;

        while (left < right && top < bottom ) {
            // 横竖
            for (int i = left; i < right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            for (int i = top ; i < bottom; i++) {
                result.add(matrix[i][right - 1]);
            }
            right--;
            if(top!=bottom){
                for (int i = right - 1; i >= left; i--) {
                    result.add(matrix[bottom - 1][i]);
                }
                bottom--;
            }

            if(left!=right){
                for (int i = bottom - 1; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }


        }
        return result.stream().mapToInt(Integer::valueOf).toArray();
    }

    @Test
    public void test(){
//        int[][] matrix = {{1,2},{3,4},{5,6},{7,8}};
//        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
//        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
//        int[][] matrix = {{1,2,3,4}};
        int[][] matrix = {};

        System.out.println(Arrays.toString(spiralOrder(matrix)));
        /**
         * 1234
         * 5678
         */
    }
}
    